package org.csu.secondhand.api.controller.fronted;

import org.csu.secondhand.api.entity.Collecting;
import org.csu.secondhand.api.entity.Dealing;
import org.csu.secondhand.api.service.CollectingService;
import org.csu.secondhand.api.service.DealingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/collecting")
public class CollectingController {
    @Autowired
    CollectingService collectingService;
    @Autowired
    DealingService dealingService;

    @PostMapping("insertCollecting")
    @ResponseBody
    public Map<Object, Object> insertCollecting(String username, long dealing) {
        Map<Object, Object> map = new HashMap<>();
        Collecting collecting = collectingService.insertCollecting(
                new Collecting(0, username, dealing));
        map.put("code", 0);
        map.put("msg", "SUCCESS");
        map.put("data", collecting);
        return map;
    }

    @PostMapping("deleteCollecting")
    @ResponseBody
    public Map<Object, Object> deleteCollecting(String username, long dealing) {
        Map<Object, Object> map = new HashMap<>();
        Collecting collecting = collectingService.deleteCollecting(username, dealing);
        map.put("code", 0);
        map.put("msg", "SUCCESS");
        map.put("data", collecting);
        return map;
    }

    @GetMapping("getCollectingByUser")
    @ResponseBody
    public Map<Object, Object> getCollectingByUser(String username) {
        Map<Object, Object> map = new HashMap<>();
        List<Collecting> collectingList = collectingService.getCollectingByUser(username);
        List<Dealing> dealingList = new ArrayList<>();
        for (int i = 0; i < collectingList.size(); i++) {
            dealingList.add(dealingService.getDealingById(collectingList.get(i).getDealing()));
        }
        map.put("code", 0);
        map.put("msg", "SUCCESS");
        map.put("data", dealingList);
        return map;
    }

    @GetMapping("doICollectIt")
    @ResponseBody
    public Map<Object, Object> doICollectIt(String username, long dealing) {
        Map<Object, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "SUCCESS");
        map.put("data", collectingService.doICollectIt(username, dealing));
        return map;
    }
}
